import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/pages/common/cry/common/application_context.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/model/application.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_form_file/sale_inquiry_form_file_upload.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';

class SaleInquiryFormFileList extends StatefulWidget {
  SaleInquiryForm? saleInquiryForm;

  SaleInquiryFormFileList({required this.saleInquiryForm, Key? key})
      : super(key: key);

  @override
  _SaleInquiryFormFileListState createState() =>
      _SaleInquiryFormFileListState();
}

class _SaleInquiryFormFileListState extends State<SaleInquiryFormFileList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  // final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);
  DmsFile dmsFile = DmsFile();
  List<DmsFile> selectedList = [];
  @override
  void initState() {
    _loadSelectVO();
    dmsFile.documentno = widget.saleInquiryForm!.inquiryNo;
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('附件名称'),
        ),
        DataColumn(
          label: Text('备注'),
        ),
        DataColumn(
          label: Text('创建人'),
        ),
        DataColumn(
          label: Text('创建日期'),
        ),
      ],
      getCells: (m) {
        DmsFile dmsFile = DmsFile.fromMap(m);
        return [
          DataCell(Text(dmsFile.name ?? '--')),
          DataCell(Text(dmsFile.remark ?? '--')),
          DataCell(Text(dmsFile.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(dmsFile.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButton(
          label: "上传",
          onPressed: () {
            _upload();
          },
          iconData: Icons.upload_rounded,
        ),
        CryButtons.download(
          context,
          selectedList.length != 1 ? null : () => _download(selectedList[0].id),
        ),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold.maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('询价表附件'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _query() {
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await DmsFileOdooApi.page(
        data: {"page": page, "domainList": dmsFile.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<DmsFile> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await DmsFileOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<DmsFile>((e) => DmsFile.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _upload() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryFormFileUpload(
          documentno: dmsFile.documentno,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _download(id) {
    //todo/web/content?model=dms.file&id=87&field=content&download=true
    Application application = ApplicationContext.instance.application;
    var odooBaseUrl = application.odooBaseUrl!;
    var data = StoreUtil.read(Constant.CLIENT);
    // http: 47.95.117.205:8099/quninmadexiazaiwenjian/admin&admin&135
    // Utils.launchURL("${odooBaseUrl}web/content?model=dms.file&id=$id&field=content&download=true");
    Utils.launchURL(
        "${odooBaseUrl}web/quninmadexiazaiwenjian/${data['login']}&${data['password']}&$id");
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.add) {
          //上传
          _upload();
        } else if (v == OperationType.edit) {
          //下载
          _download(selectedList[0].id);
          // downloadFile(selectedList[0].id);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete, (context) async {
            _delete(selectedList);
          });
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.upload_rounded),
            title: Text('上传'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            enabled: selectedList.length == 1,
            leading: const Icon(Icons.download_rounded),
            title: Text('下载'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
